package team.tunan.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.SessionStatus;
import team.tunan.common.Result;
import team.tunan.entity.User;
import team.tunan.service.IUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sqx
 * @since 2024-01-01
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/userlist")
    public String userManager(Model model, HttpServletRequest request) {
        List<User> allUser = userService.getAllUser(request);
        long count = allUser.stream().count();
        model.addAttribute("count",count);
        model.addAttribute("users",allUser);
        return "user/userlist";
    }

    @RequestMapping("/add")
    public String add(){
        return "user/add";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable Integer id, Model model){
        model.addAttribute("user",userService.getUserById(id));

        System.out.println(userService.getUserById(id));
        return "user/update";
    }

    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable Integer id,Model model){
        model.addAttribute("user",userService.getUserById(id));
        System.out.println(userService.getUserById(id));
        return "user/detail";
    }

    @RequestMapping("/doadd")
    @ResponseBody
    public Result doAdd(User user){
        int add = userService.add(user);
        if (add>0){
            return new Result("成功",null,true);
        }
        return new Result("失败",null,false);
    }

    @RequestMapping("/doupdate")
    @ResponseBody
    public Result doUpdate(User user){
        int update = userService.update(user);
        System.out.println("update = " + user);
        if (update>0){
            return new Result("成功",user,true);
        }
        return new Result("失败",null,false);
    }


    @RequestMapping("/del/{userid}")
    public String del(@PathVariable Integer userid){
        userService.del(userid);
        return "redirect:/user/userlist";
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session, SessionStatus sessionStatus){
        session.invalidate();
        sessionStatus.setComplete();
        return "redirect:/main";
    }

}

